package com.sh.dc.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sh.dc.common.enums.AlgoTaskStatusEnum;
import com.sh.dc.common.enums.TaskStatusEnum;
import com.sh.dc.common.pojo.dto.TaskAlgoDto;
import com.sh.dc.common.pojo.dto.TaskSolverDto;
import com.sh.dc.common.pojo.query.TaskAlgoPageQuery;
import com.sh.dc.entity.TaskAlgo;
import com.sh.dc.entity.TaskSolver;
import com.sh.dc.mapper.TaskAlgoMapper;
import com.sh.dc.service.ITaskAlgoService;
import io.micrometer.common.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class TaskAlgoServiceImpl extends ServiceImpl<TaskAlgoMapper, TaskAlgo> implements ITaskAlgoService {

    @Autowired
    private TaskAlgoMapper taskAlgoMapper;

    @Override
    public TaskAlgoDto transferToDto(TaskAlgo taskAlgo) {
        if (taskAlgo == null) {
            return null;
        }
        TaskAlgoDto taskAlgoDto = new TaskAlgoDto();
        BeanUtil.copyProperties(taskAlgo, taskAlgoDto);
        if (StringUtils.isNotBlank(taskAlgo.getStatus())) {
            taskAlgoDto.setStatusName(AlgoTaskStatusEnum.getNameByCode(taskAlgo.getStatus()));
        }
        return taskAlgoDto;
    }

    @Override
    public IPage<TaskAlgoDto> getTaskAlgoPage(TaskAlgoPageQuery query) {
        Page<TaskAlgo> page = new Page<>(query.getPageNum(), query.getPageSize());
        page.addOrder(OrderItem.desc("id"));
        QueryWrapper<TaskAlgo> queryWrapper = new QueryWrapper<>();
        // 由于result字段可能比较大，这里只查询指定字段
        queryWrapper.select("id", "tid", "name", "status", "algo_id", "algo_name",
                "start_time", "end_time", "create_time", "create_by");
        if (StringUtils.isNotBlank(query.getName())) {
            queryWrapper.like("name", query.getName());
        }
        if (StringUtils.isNotBlank(query.getAlgoName())) {
            queryWrapper.like("algo_name", query.getAlgoName());
        }
        if (query.getStartTime() != null && query.getEndTime() != null) {
            queryWrapper.between("create_time", query.getStartTime(), query.getEndTime());
        }
        IPage<TaskAlgo> result = taskAlgoMapper.selectPage(page, queryWrapper);
        return result.convert(this::transferToDto);
    }
}
